<?php
namespace app\common\model;
use think\facade\Cache;
use think\Model;

class Nav extends TimeModel
{

    static function onAfterInsert(Model $model)
    {
        $cacheName = 'nav_' . $model->position;
        if (Cache::has($cacheName)) {
            Cache::delete($cacheName);
        }
    }
    static function onAfterDelete(Model $model)
    {
        $cacheName = 'nav_' . $model->position;
        if (Cache::has($cacheName)) {
            Cache::delete($cacheName);
        }
    }
    static function onAfterUpdate(Model $model)
    {
        $cacheName = 'nav_' . $model->position;
        if (Cache::has($cacheName)) {
            Cache::delete($cacheName);
        }
    }

    public static function getItems($position=1){
        $cacheName = 'nav_' . $position;
        if (Cache::has($cacheName)) {
            $list=Cache::get($cacheName);
        }else{
            $data = (new static())->where('position',$position)->field('id,pid,title,short_title,icon,link')
                ->where('status',1)
                ->order('sort','desc')
                ->select()
                ->toArray();
            $list = self::generateTree($data);
            Cache::set($cacheName,$list);
        }
        return $list;
    }

    public static function getPidCateList($position){
        $list = (new static())->where('position',$position)->field('id,pid,title')
            ->order('sort','desc')
            ->select()
            ->toArray();
        $pidList = buildPidTree(0, $list);
        $pidList = array_merge([[
            'id'    => 0,
            'pid'   => 0,
            'title' => '顶级菜单',
        ]], $pidList);
        return $pidList;
    }



    static function generateTree($array){
        //第一步 构造数据
        $items = array();
        foreach($array as $value){
            $value['son'] = array();
            $items[$value['id']] = $value;
        }
        $tree = array();
        foreach($items as $key => $value){
            if(isset($items[$value['pid']])){
                $items[$value['pid']]['son'][] = &$items[$key];
            }else{
                $tree[] = &$items[$key];
            }
        }
        return $tree;
    }
}